/*Copyright 2014 Rajesh Putta

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
 * 
 */

package com.codesnippets4all.xss.request;

import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;

import com.codesnippets4all.xss.config.handlers.XSSConfigHandler;
import com.codesnippets4all.xss.exceptions.XSSFilterRuntimeException;

/*
 * This component applies patterns on request parameters if they are configured under xss-patterns.xml file to avoid possible performance issues
 * in a web application with more number of request parameters and most of them need not be validated for XSS attacks
 */
public class XSSAttacksPreventionRequestWrapper extends
		HttpServletRequestWrapper {
	private HttpServletRequest request = null;
	private HttpServletResponse response = null;

	private String attackAction = null;

	public XSSAttacksPreventionRequestWrapper(HttpServletRequest request) {
		super(request);
		this.request = request;
	}

	public void setResponse(HttpServletResponse response) {
		this.response = response;
	}

	public void setAttackAction(String attackAction) {
		this.attackAction = attackAction;
	}

	@Override
	public String[] getParameterValues(String parameter) {
		String[] values = this.request.getParameterValues(parameter);

		if (values == null) {
			return null;
		}

		List<String> parameterList = XSSConfigHandler.getInstance()
				.getParameters();

		if (parameterList != null && !parameterList.isEmpty()) {
			// search if the current requested parameter name is configured for
			// XSS attack prevention
			int position = Collections.binarySearch(parameterList, parameter);

			if (position < 0) {
				return values;
			}
		}

		String[] finalValues = new String[values.length];
		for (int i = 0; i < values.length; i++) {
			finalValues[i] = applyAction(values[i]);
		}

		return finalValues;
	}

	@Override
	public String getParameter(String parameter) {
		String value = this.request.getParameter(parameter);

		List<String> parameterList = XSSConfigHandler.getInstance()
				.getParameters();

		if (parameterList != null && !parameterList.isEmpty()) {
			// search if the current requested parameter name is configured for
			// XSS attack prevention
			int position = Collections.binarySearch(parameterList, parameter);

			if (position < 0) {
				return value;
			}
		}

		return applyAction(value);
	}

	@Override
	public String getHeader(String name) {
		String value = this.request.getHeader(name);

		List<String> headerList = XSSConfigHandler.getInstance().getHeaders();

		if (headerList != null && !headerList.isEmpty()) {
			// search if the current requested header name is configured for XSS
			// attack prevention
			int position = Collections.binarySearch(headerList, name);

			if (position < 0) {
				return value;
			}
		}

		return applyAction(value);
	}

	private String applyAction(String value) {
		if (value != null) {

			List<Pattern> patternList = XSSConfigHandler.getInstance()
					.getPatterns();

			for (Pattern xsspattern : patternList) {
				Matcher matcher = xsspattern.matcher(value);

				if (matcher.find()) {
					if (!attackAction.equals("cleanup")) {
						try {
							this.request.getRequestDispatcher(attackAction)
									.forward(this.request, this.response);
						} catch (ServletException e) {
							throw new XSSFilterRuntimeException(e);
						} catch (IOException e) {
							throw new XSSFilterRuntimeException(e);
						}
					} else {
						value = matcher.replaceAll("");
					}
				}

			}
		}
		return value;
	}
}